package reflect;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URISyntaxException;

/**
 * 调用与当前类Test7在同一个包中所有类里那些本类自己定义的公开，无参且名字中含有字母s的方法
 */
public class Test7 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class c = Test7.class;
        String packname = c.getPackage().getName();
        File file = new File(Test7.class.getResource(".").toURI());
        File[] subs = file.listFiles(f->f.getName().endsWith(".class"));
        for(File sub : subs) {
            String filename = sub.getName();
            String className = filename.replace(".class","");
            Class cls = Class.forName(packname+"."+className);
            Object o = cls.newInstance();
            Method[] methods = cls.getDeclaredMethods();
            for(Method method : methods) {
                if(
                        method.getModifiers()== Modifier.PUBLIC
                        &&
                                method.getParameterCount()==0
                        &&
                                method.getName().contains("s")
                ){
                    System.out.println("要求的调用方法为："+method.getName()+"()");
                    method.invoke(o);
                }
            }
        }
    }
}
